<template>
  <div class="interactive">
    <!-- 信息输入框 -->
    <ul class="user_info">
      <li class="info_item" v-show="mounType !== 'yjfankui'">
        <span>附近山体</span>
        <span @click="nearbyMoun">{{ msgMoun }}</span>
        <ul class="dropdown-menu" v-show="isShowDropdown">
          <li
            class="dropdown-menu-item"
            v-for="item in mountainList"
            :key="item.id"
            @click="selectMoun(item)"
          >
            {{ item.mountain_name }}
          </li>
          <li class="dropdown-menu-item" v-show="mountainList.length <= 0">
            暂无附近山体数据
          </li>
        </ul>
      </li>
      <li class="info_item">
        <span>姓名</span>
        <input type="text" v-model="username" placeholder="上报人姓名" />
      </li>

      <li class="info_item">
        <span>手机号</span>
        <input type="text" v-model="phone" placeholder="输入上报人手机号" />
      </li>

      <li class="info_item" v-show="mounType !== 'sjshangbao'">
        <span>标题</span>
        <input type="text" v-model="title" placeholder="请输入标题" />
      </li>

      <li
        class="info_item"
        style="display: block"
        v-show="mounType == 'sjshangbao'"
      >
        <!-- <span style="display: block">选择时间</span>
        <span
          @click="currentTimes = true"
          style="display: block; width: 100%; height: 100%; color:#999"
        >{{times | timess}}</span>
        <van-datetime-picker
          v-model="currentDate"
          @confirm="confirm"
          @cancel="currentTimes = false"
          type="datetime"
          v-show="currentTimes"
          title="选择上报时间"
          :min-date="minDate"
          :max-date="maxDate"
        /> -->
      </li>

      <li class="info_item">
        <label for="desc">
          <span>事件描述</span>
        </label>
        <textarea
          class="textarea"
          v-model="desc"
          name
          id="desc"
          cols="30"
          rows="10"
          placeholder="在这里输入内容字数不超过200字"
        ></textarea>
        <div class="uploader">
          <van-uploader
            icon="plus"
            v-model="fileList"
            multiple
            max-count="3"
            :after-read="afterRead"
            :before-delete="beforeDelete"
          />
          <span>{{ fileList.length }}/3</span>
        </div>
      </li>
    </ul>
    <div class="inter_btn" @click="subSuper">
      <span>提交</span>
    </div>
  </div>
</template>

<script>
import {
  subSuperviseInfo,
  setInspection,
  subInteractiveInfo,
  getUserdetail,
} from "api/interactive";
import { uploader } from "api/upload";
import { authLogin } from "api/reporting";
import { getSignPackage } from "api/home";
// 获取坐标
import { getNearbyMountain } from "api/news";

export default {
  name: "Interactive",
  data() {
    return {
      //类型
      mounType: "",
      // 图片列表
      fileList: [],
      // 选择山体
      msgMoun: "请选择山体",
      currentMun: "",
      username: "",
      phone: "",
      title: "",
      desc: "",
      openid: "",
      mountainList: "",
      longitude: null,
      latitude: null,
      winUrl: "",
      // 时间
      times: "",
      currentTimes: false,
      // 是否显示下拉
      isShowDropdown: false,
      imgHotUrls: [],
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
    };
  },
  methods: {
    afterRead(file) {
      if (file.length) {
        for (let i = 0; i < file.length; i++) {
          let files = { file: file[i].content, name: file[i].file.name };
          uploader(files)
            .then((res) => {
              this.imgHotUrls.push("http://image.sdxing.cn/" + res.data.data);
              this.$toast({
                message: res.data.msg,
              });
            })
            .catch((err) => {
              console.log(err);
            });
        }
      } else {
        let files = { file: file.content, name: file.file.name };
        uploader(files)
          .then((res) => {
            this.imgHotUrls.push("http://image.sdxing.cn/" + res.data.data);
            this.$toast({
              message: res.data.msg,
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 删除图片
    beforeDelete(file, detail) {
      this.imgHotUrls.splice(detail.index, 1);
      return true;
    },
    // 时间选择
    confirm(info) {
      this.times = this.$moment(info).format("YYYY-MM-DD HH:mm:ss");
      this.currentTimes = false;
    },
    // 提交
    subSuper() {
      let data = "";
      // 上报事件页面
      if (this.mounType == "sjshangbao") {
        data = {
          openid: this.openid,
          inspection_des: this.desc,
          mountain_id: this.currentMun.id || "",
          nickname: this.username,
          mobile: this.phone,
          happen_time: this.currentMun.create_at || "",
          longitude: this.currentMun.longitude || "",
          latitude: this.currentMun.latitude || "",
          detail: this.currentMun.location || "",
          // happen_time: this.times,
          inspection_img: this.imgHotUrls.join("|"),
        };
        setInspection(data).then((res) => {
          if (res.code == 200) {
            this.$toast({
              message: res.msg,
            });
            // 清空data数据
            Object.assign(this.$data, this.$options.data());
            this.$router.push({ name: "Reporting" });
          } else {
            this.$toast({
              message: res.msg,
            });
          }
        });
      } else if (this.mounType == "hdcanyu") {
        data = {
          openid: this.openid,
          title: this.title,
          desc: this.desc,
          longitude: this.longitude,
          latitude: this.latitude,
          mountain_id: this.currentMun.id || "",
          img: this.imgHotUrls.join("|"),
          username: this.username,
          phone: this.phone,
        };
        subInteractiveInfo(data).then((res) => {
          if (res.code == 200) {
            this.$toast({
              message: res.msg,
            });
            // 清空data数据
            Object.assign(this.$data, this.$options.data());
            this.$router.push({ name: "MyUpload" });
          } else {
            this.$toast({
              message: res.msg,
            });
          }
        });
      } else {
        // 意见反馈
        data = {
          openid: this.openid,
          username: this.username,
          phone: this.phone,
          title: this.title,
          desc: this.desc,
          img: this.imgHotUrls.join("|"),
        };
        subSuperviseInfo(data).then((res) => {
          if (res.code == 200) {
            this.$toast({
              message: res.msg,
            });
            // 清空data数据
            Object.assign(this.$data, this.$options.data());
            this.$router.push({ name: "Supervise" });
          } else {
            this.$toast({
              message: res.msg,
            });
          }
        });
      }
    },
    // 获取附近山
    nearbyMoun() {
      let that = this;
      if (that.longitude) {
        getNearbyMountain(that.longitude, that.latitude).then((res) => {
          if (res.code == 200) {
            that.mountainList = res.data;
            that.isShowDropdown = true;
          } else {
            this.$toast({
              message: res.msg,
            });
            that.isShowDropdown = false;
          }
        });
      } else {
        // location.href
        getSignPackage(this.winUrl).then((res) => {
          let that = this;
          if (res.code == 200) {
            // 配置 JS-SDK
            that.wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: res.data.signPackage.appId, // 必填，公众号的唯一标识
              timestamp: res.data.signPackage.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.data.signPackage.nonceStr, // 必填，生成签名的随机串
              signature: res.data.signPackage.signature, // 必填，签名
              jsApiList: ["scanQRCode", "getLocation"], // 必填，需要使用的JS接口列表
            });
            that.wx.ready(() => {
              that.wx.getLocation({
                type: "gcj02",
                success: function (res) {
                  // latitude;  纬度，浮点数，范围为90 ~ -90
                  // longitude;  经度，浮点数，范围为180 ~ -180。
                  let lat = res.latitude;
                  let lng = res.longitude;
                  let x_PI = (3.14159265358979324 * 3000.0) / 180.0;
                  let z =
                    Math.sqrt(lng * lng + lat * lat) +
                    0.00002 * Math.sin(lat * x_PI);
                  let theta =
                    Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
                  that.longitude = z * Math.cos(theta) + 0.0065;
                  that.latitude = z * Math.sin(theta) + 0.006;
                  that.nearbyMoun();
                },
              });
            });
          }
        });
      }
    },
    // 选择山体
    selectMoun(item) {
      this.currentMun = item;
      this.msgMoun = item.mountain_name;
      this.longitude = item.longitude;
      this.latitude = item.latitude;
      this.isShowDropdown = false;
    },
    getUserdetail() {
      let token = localStorage.getItem("token");
      getUserdetail(token).then((res) => { 
        if(res.code == 200){
          this.username = res.data.name
          this.phone = res.data.phone 
        }
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    let u = navigator.userAgent;
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // XXX: 修复iOS版微信HTML5 History兼容性问题
    if (isiOS && to.path !== location.pathname) {
      // 此处不可使用location.replace
      location.replace(to.fullPath);
    } else {
      next();
    }
  },
  filters: {
    timess(item) {
      if (!item) {
        return "选择上报时间";
      } else {
        return item;
      }
    },
  },
  // watch:{
  //   times(info){
  //     this.times = info
  //   }
  // },
  mounted() {
    this.winUrl = location.href;
    this.openid = localStorage.getItem("openid");
    this.mounType = this.$route.query.type; 
    if (this.mounType == "sjshangbao") {
      this.getUserdetail(); 
    }
  },
};
</script>

<style lang="less" scoped>
.interactive {
  padding: 0 14px;
  .user_info {
    .info_item {
      display: flex;
      justify-content: space-between;
      font-size: 16px;
      color: #383838;
      line-height: 60px;
      border-bottom: 1px solid #f5f5f5;
      span {
        width: 100px;
      }
      input {
        flex: 1;
        font-size: 16px;
      }
      .dropdown-menu {
        padding: 6px;
        position: absolute;
        top: 50px;
        right: 30px;
        min-width: 80px;
        height: 200px;
        overflow: hidden;
        overflow-y: scroll;
        background: #fff;
        border: 1px solid #eee;
        border-radius: 6px;
        .dropdown-menu-item {
          height: 30px;
          line-height: 30px;
          border-bottom: 1px solid #eee;
        }
      }
    }
    & .info_item:last-child {
      flex-direction: column;
      .textarea {
        padding: 0 12px;
        font-size: 14px;
        height: 176px;
        border: none;
        background: #f3f3f5;
        border-radius: 8px;
      }
      .uploader {
        display: flex;
        position: relative;
        top: -90px;
        left: 20px;
        height: 80px;
        .van-uploader {
          width: 100%;
        }
        span {
          margin-left: 10px;
          line-height: 130px;
          color: #9e9ea0;
          font-size: 20px;
        }
      }
    }
  }
  .inter_btn {
    width: 345px;
    height: 45px;
    line-height: 45px;
    text-align: center;
    color: #fff;
    font-size: 18px;
    background: linear-gradient(#2db88f 0%, #28c08d 99%);
    border-radius: 23px;
  }
}
</style>